﻿namespace SuperMarieApi.App.Controllers.Bll
{
    using FaceppSDK;
    using SuperMarieApi.App.Controllers.Biz;
    using SuperMarieApi.App.Controllers.Entity;
    using SuperMarieApi.App.Controllers.Framework.Config;
    using SuperMarieApi.App.Controllers.Framework.DataAccess;
    using SuperMarieFaceBiz;
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Text;

    public class AppRootBiz
    {


        /// <summary>
        /// 读取图片
        /// </summary>
        /// <param name="MyImg_ID">图片主键</param>
        /// <returns></returns>
        public static DetectResult ReadImage(int MyImg_ID)
        {
            MyImgEntity img = MyImgBiz.GetMyImgObj(MyImg_ID);
            FaceBizTool facebiz = new FaceBizTool();
            DetectResult res = facebiz.ReadImage(img.FilePath);
            return res;
        }

        /// <summary>
        /// 判断相似度
        /// </summary> 
        /// <param name="face_id1"></param>
        /// <param name="face_id2"></param>
        /// <returns></returns>
        public static CompareResult CompareImage(string face_id1, string face_id2)
        {
            FaceBizTool facebiz = new FaceBizTool();
            CompareResult res = facebiz.CompareImage(face_id1, face_id2);
            return res;
        }

        /// <summary>
        /// 给当前用户推送他匹配的音乐
        /// </summary>
        /// <param name="face_id"></param>
        /// <returns></returns>
        public static List<MyMusicLabEntity> ReadMusic(string face_id)
        {
            SetCompareImageResult(face_id);
            return GetSimilarityFaceIdMusic(face_id);
        }

        /// <summary>
        /// 点赞
        /// </summary>
        /// <param name="MyMusicLab_ID">主键</param>
        /// <returns></returns>
        public static void Zan(int MyMusicLab_ID)
        {
            SetMyMusicLabZannum(MyMusicLab_ID);
        }

        private static List<MyMusicLabEntity> GetSimilarityFaceIdMusic(string face_id)
        {
            DataCommand cmd = DataCommandManager.GetDataCommand("SuperMarieApi.Get-SimilarityFaceIdMusic");
            cmd.SetParameterValue("@face_id", face_id);
            List<MyMusicLabEntity> lists = cmd.ExecuteEntityList<MyMusicLabEntity>();
            return lists;
        }

        private static List<MyFaceEntity> GetSimilarityFaceId(string face_id)
        {
            DataCommand cmd = DataCommandManager.GetDataCommand("SuperMarieApi.Get-SimilarityFaceId");
            cmd.SetParameterValue("@face_id", face_id);
            List<MyFaceEntity> lists = cmd.ExecuteEntityList<MyFaceEntity>();
            return lists;
        }

        private static int SetSimilarityFaceId(string xml)
        {
            DataCommand cmd = DataCommandManager.GetDataCommand("SuperMarieApi.Set-SimilarityFaceIdByXml");
            cmd.SetParameterValue("@MyFaceSimilarityXML", xml);
            return cmd.ExecuteNonQuery();
        }

        private static int SetMyMusicLabZannum(int MyMusicLab_ID)
        {
            DataCommand cmd = DataCommandManager.GetDataCommand("SuperMarieApi.SetMyMusicLabZannum");
            cmd.SetParameterValue("@MyMusicLab_ID", MyMusicLab_ID);
            return cmd.ExecuteNonQuery();
        }

        /// <summary>
        /// 存储相似度
        /// </summary> 
        /// <param name="face_id1"></param>
        /// <returns></returns>
        public static void SetCompareImageResult(string face_id1)
        {
            List<MyFaceEntity> myfaceidlist = GetSimilarityFaceId(face_id1);
            List<MyFaceSimilarityEntity> list = new List<MyFaceSimilarityEntity>();
            foreach (var face in myfaceidlist)
            {
                FaceBizTool facebiz = new FaceBizTool();
                CompareResult res = facebiz.CompareImage(face_id1, face.face_id);
                //存储
                MyFaceSimilarityEntity entity = new MyFaceSimilarityEntity();

                entity.face_id = face_id1;
                entity.other_face_id = face.face_id;
                entity.similarity = (decimal)res.similarity;
                entity.AddTime = DateTime.Now;
                list.Add(entity);
                //MyFaceSimilarityBiz.InsertMyFaceSimilarityObj(entity);
            }
            if (list.Count > 0)
            {
                string setxml = MyFaceSimilarityListToXml(list);
                SetSimilarityFaceId(setxml);
            }
        }

        /// <summary>
        /// 插入MyFaceSimilarity详情
        /// </summary>
        /// <returns></returns>
        public static int InsertMyFaceSimilarityObj(MyFaceSimilarityEntity obj)
        {
            DataCommand cmd = DataCommandManager.GetDataCommand("SuperMarieApi.Insert-MyFaceSimilarity");
            cmd.SetParameterValue("@face_id", obj.face_id);
            cmd.SetParameterValue("@other_face_id", obj.other_face_id);
            cmd.SetParameterValue("@similarity", obj.similarity);
            cmd.SetParameterValue("@AddTime", obj.AddTime);
            object identity = cmd.ExecuteScalar();
            if (identity == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(identity);
            }
        }

        /// <summary>
        ///MyFaceSimilarity对象List转换成XML字符串
        /// </summary>
        public static string MyFaceSimilarityListToXml(List<MyFaceSimilarityEntity> objlist)
        {
            StringBuilder MyFaceSimilarityXml = new StringBuilder();
            foreach (var obj in objlist)
            {
                MyFaceSimilarityXml.Append("<MyFaceSimilarity>");
                MyFaceSimilarityXml.Append("<face_id>" + obj.face_id + "</face_id>");
                MyFaceSimilarityXml.Append("<other_face_id>" + obj.other_face_id + "</other_face_id>");
                MyFaceSimilarityXml.Append("<similarity>" + obj.similarity + "</similarity>");
                MyFaceSimilarityXml.Append("<AddTime>" + obj.AddTime + "</AddTime>");
                MyFaceSimilarityXml.Append("</MyFaceSimilarity>");
            }
            return MyFaceSimilarityXml.ToString();
        }



        //图片 转为    base64编码的文本
        public static void ImgToBase64String(string Imagefilename)
        {
            try
            {
                Bitmap bmp = new Bitmap(Imagefilename);

                FileStream fs = new FileStream(Imagefilename + ".txt", FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);

                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                String strbaser64 = Convert.ToBase64String(arr);
                sw.Write(strbaser64);

                sw.Close();
                fs.Close();
                // MessageBox.Show("转换成功!");
            }
            catch (Exception ex)
            {

            }
        }


        //base64编码的文本 转为    图片
        public static List<string> Base64StringToImage(string base64)
        {
            List<string> files = new List<string>();
            string dummyData = base64;
            try
            {

                //过滤特殊字符即可   
                //dummyData = base64.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
                //if (dummyData.Length % 4 > 0)
                //{
                //    dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
                //}
                dummyData = dummyData.Split(',')[1];

            }
            catch (System.Exception exp)
            {
                // Error creating stream or reading from it.
                System.Console.WriteLine("{0}", exp.Message);

            }

            try
            {
                byte[] arr = Convert.FromBase64String(dummyData);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                string filepath = "";
                string urlpath = "";
                foreach (var kv in ConfigManager.GetKeyValuePair("path"))
                {
                    if (kv.Key.ToLower() == "filepath")
                    {
                        filepath = kv.Value;
                        //break;
                    }
                    if (kv.Key.ToLower() == "urlpath")
                    {
                        urlpath = kv.Value;
                        //break;
                    }
                }
                string temp = DateTime.Now.ToString("\\\\yyMM\\\\dd\\\\HH\\\\") + Guid.NewGuid().ToString();
                string savefilepath = filepath + temp + ".png";
                string saveurlpath = urlpath + temp + ".png";
                files.Add(savefilepath);
                files.Add(saveurlpath);
                string newDir = new System.IO.FileInfo(savefilepath).DirectoryName; // 新文件所在目录。。
                //创建本地文件路径
                if (!Directory.Exists(newDir))
                {
                    Directory.CreateDirectory(newDir);
                }
                bmp.Save(savefilepath, ImageFormat.Png);
                ms.Close();

            }
            catch (Exception ex)
            {

            }
            return files;
        }
    }
}
